<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>交作业我灭火！V5</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Arial Rounded MT Bold', 'Microsoft YaHei', sans-serif;
        }
        
        body {
            background: linear-gradient(135deg, #e6f7ff, #b3e0ff);
            min-height: 100vh;
            padding: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .container {
            max-width: 1200px;
            width: 100%;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 20px;
            box-shadow: 0 10px 30px rgba(0, 120, 215, 0.2);
            padding: 25px;
            margin-top: 20px;
        }
        
        header {
            text-align: center;
            margin-bottom: 25px;
            position: relative;
        }
        
        h1 {
            color: #0066cc;
            font-size: 3.2rem;
            text-shadow: 3px 3px 5px rgba(0, 0, 0, 0.1);
            margin-bottom: 10px;
            background: linear-gradient(to right, #ff6b6b, #ff8e53);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            padding: 15px 0;
            position: relative;
        }
        
        h1::after {
            content: "";
            position: absolute;
            bottom: 0;
            left: 25%;
            width: 50%;
            height: 5px;
            background: linear-gradient(to right, #ff9a9e, #fad0c4);
            border-radius: 10px;
        }
        
        .date-bar {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: linear-gradient(to right, #4facfe, #00f2fe);
            padding: 15px 25px;
            border-radius: 15px;
            box-shadow: 0 4px 15px rgba(0, 102, 204, 0.2);
            color: white;
            font-size: 1.4rem;
            margin-bottom: 30px;
            flex-wrap: wrap;
            gap: 10px;
        }
        
        .button-group {
            display: flex;
            gap: 5px;
        }
        
        .import-export-buttons {
            display: flex;
            gap: 8px;
        }
        
        .date-bar button {
            background: white;
            color: #0066cc;
            border: none;
            padding: 10px 20px;
            border-radius: 50px;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 4px 10px rgba(0, 102, 204, 0.3);
            display: flex;
            align-items: center;
            gap: 8px;
        }
        
        .date-bar button:hover {
            transform: translateY(-3px);
            box-shadow: 0 6px 15px rgba(0, 102, 204, 0.4);
        }
        
        .date-bar button:active {
            transform: translateY(1px);
        }
        
        /* 教室布局样式 */
        .classroom {
            display: flex;
            flex-direction: column;
            gap: 30px;
            margin-bottom: 30px;
        }
        
        .teacher-area {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 100%;
            gap: 20px;
        }
        
        .teacher-desk {
            flex: 0 0 60%;
            height: 80px;
            background: linear-gradient(135deg, #8B4513, #A0522D);
            border-radius: 15px;
            display: flex;
            justify-content: center;
            align-items: center;
            color: white;
            font-size: 1.5rem;
            font-weight: bold;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .front-left, .front-right {
            display: flex;
            gap: 15px;
            flex: 0 0 auto;
        }
        
        .groups-container {
            display: flex;
            width: 100%;
            gap: 20px;
            justify-content: center;
            flex-wrap: wrap;
        }
        
        .student-group {
            display: flex;
            flex-direction: column;
            gap: 15px;
            width: 22%;
            min-width: 200px;
            border-radius: 15px;
            overflow: hidden;
            transition: all 0.3s;
        }
        
        /* 四组不同颜色 */
        .group-1 {
            background-color: rgba(255, 193, 7, 0.1);
            border: 2px solid #ffc107;
        }
        
        .group-2 {
            background-color: rgba(76, 175, 80, 0.1);
            border: 2px solid #4caf50;
        }
        
        .group-3 {
            background-color: rgba(33, 150, 243, 0.1);
            border: 2px solid #2196f3;
        }
        
        .group-4 {
            background-color: rgba(156, 39, 176, 0.1);
            border: 2px solid #9c27b0;
        }
        
        .group-title {
            text-align: center;
            font-weight: bold;
            font-size: 1.2rem;
            padding: 10px;
            border-radius: 10px 10px 0 0;
            box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
            transition: all 0.3s;
            cursor: pointer;
            user-select: none;
        }
        
        /* 组标题标题颜色 */
        .group-1 .group-title {
            background-color: #ffc107;
            color: #fff;
        }
        
        .group-2 .group-title {
            background-color: #4caf50;
            color: #fff;
        }
        
        .group-3 .group-title {
            background-color: #2196f3;
            color: #fff;
        }
        
        .group-4 .group-title {
            background-color: #9c27b0;
            color: #fff;
        }
        
        .group-title:hover {
            transform: translateY(-3px);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .group-title.completed {
            opacity: 0.8;
            box-shadow: 0 0 15px rgba(0, 0, 0, 0.3) inset;
        }
        
        /* 同桌学生在同一行 */
        .group-students {
            display: flex;
            flex-direction: column;
            gap: 15px;
            padding: 15px;
        }
        
        .student-row {
            display: flex;
            gap: 15px;
            min-height: 80px;
        }
        
        .fire-item {
            flex: 1;
            position: relative;
            height: 80px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            transition: all 0.3s ease;
            border-radius: 15px;
            background: rgba(255, 255, 255, 0.8);
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
            padding: 10px;
            user-select: none;
        }
        
        /* 学生卡片边框颜色 - 与组对应 */
        .fire-item.group-1 {
            border: 1px solid #ffc107;
        }
        
        .fire-item.group-2 {
            border: 1px solid #4caf50;
        }
        
        .fire-item.group-3 {
            border: 1px solid #2196f3;
        }
        
        .fire-item.group-4 {
            border: 1px solid #9c27b0;
        }
        
        .student-id {
            position: absolute;
            top: 5px;
            right: 5px;
            font-size: 0.7rem;
            color: #999;
            background: rgba(255, 255, 255, 0.7);
            padding: 2px 5px;
            border-radius: 3px;
        }
        
        .fire-item:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 20px rgba(255, 107, 107, 0.3);
        }
        
        .fire-icon {
            font-size: 1.8rem;
            margin-bottom: 5px;
            text-shadow: 0 0 10px rgba(255, 107, 107, 0.5);
            transition: all 0.3s;
            color: #ff6b6b;
        }
        
        .fire-item.completed .fire-icon {
            color: #a0a0a0;
            text-shadow: none;
            filter: grayscale(100%);
        }
        
        .student-name {
            font-size: 1rem;
            font-weight: bold;
            text-align: center;
            word-break: break-word;
            max-width: 100%;
        }
        
        /* 学生姓名颜色 - 与组对应 */
        .fire-item.group-1 .student-name {
            color: #e65100;
        }
        
        .fire-item.group-2 .student-name {
            color: #2e7d32;
        }
        
        .fire-item.group-3 .student-name {
            color: #0d47a1;
        }
        
        .fire-item.group-4 .student-name {
            color: #4a148c;
        }
        
        .fire-item.completed .student-name {
            color: #666;
        }
        
        /* 对话框样式 */
        .dialog-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.7);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
            opacity: 0;
            pointer-events: none;
            transition: opacity 0.3s;
        }
        
        .dialog-overlay.active {
            opacity: 1;
            pointer-events: all;
        }
        
        .congrats-dialog {
            background: linear-gradient(135deg, #ff9a9e, #fad0c4);
            border-radius: 25px;
            padding: 40px;
            text-align: center;
            max-width: 600px;
            width: 90%;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
            transform: scale(0.8);
            transition: transform 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
        }
        
        .dialog-overlay.active .congrats-dialog {
            transform: scale(1);
        }
        
        .group-congrats-dialog, .info-dialog {
            background: linear-gradient(135deg, #4facfe, #00f2fe);
        }
        
        .congrats-dialog h2 {
            font-size: 4rem;
            color: #fff;
            text-shadow: 3px 3px 5px rgba(0, 0, 0, 0.2);
            margin-bottom: 30px;
        }
        
        .congrats-dialog p {
            font-size: 1.8rem;
            color: white;
            margin-bottom: 30px;
            text-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2);
        }
        
        .congrats-dialog button {
            background: white;
            color: #ff6b6b;
            border: none;
            padding: 15px 40px;
            border-radius: 50px;
            font-size: 1.5rem;
            font-weight: bold;
            cursor: pointer;
            transition: all 0.3s;
            box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2);
        }
        
        .group-congrats-dialog button, .info-dialog button {
            color: #0066cc;
        }
        
        .congrats-dialog button:hover {
            transform: scale(1.05);
            box-shadow: 0 8px 20px rgba(0, 0, 0, 0.3);
        }
        
        .fire-particle {
            position: absolute;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            opacity: 0;
            background: #ff6b6b;
        }
        
        .instructions {
            background: white;
            border-radius: 15px;
            padding: 20px;
            margin-top: 30px;
            box-shadow: 0 5px 15px rgba(0, 102, 204, 0.1);
            max-width: 800px;
            width: 100%;
        }
        
        .instructions h3 {
            color: #0066cc;
            margin-bottom: 15px;
            text-align: center;
            font-size: 1.6rem;
        }
        
        .instructions ul {
            padding-left: 25px;
        }
        
        .instructions li {
            margin-bottom: 10px;
            color: #333;
            line-height: 1.6;
        }
        
        .sync-indicator {
            position: fixed;
            bottom: 20px;
            right: 20px;
            background: #4CAF50;
            color: white;
            padding: 10px 20px;
            border-radius: 50px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
            display: flex;
            align-items: center;
            gap: 10px;
            opacity: 0;
            transform: translateY(20px);
            transition: all 0.5s;
        }
        
        .sync-indicator.active {
            opacity: 1;
            transform: translateY(0);
        }
        
        /* 导入提示对话框 */
        .import-guide {
            text-align: left;
            margin-bottom: 20px;
        }
        
        .import-guide h4 {
            margin-bottom: 10px;
            font-size: 1.2rem;
        }
        
        .import-guide ul {
            padding-left: 20px;
            margin-bottom: 10px;
        }
        
        .import-guide li {
            margin-bottom: 5px;
            font-size: 1rem;
        }
        
        @media (max-width: 1200px) {
            .groups-container {
                flex-wrap: wrap;
            }
            
            .student-group {
                width: 45%;
            }
        }
        
        @media (max-width: 900px) {
            h1 {
                font-size: 2.5rem;
            }
            
            .teacher-desk {
                flex: 0 0 50%;
            }
        }
        
        @media (max-width: 600px) {
            .date-bar {
                flex-direction: column;
                gap: 15px;
                padding: 15px;
            }
            
            .date-bar span {
                order: -1;
            }
            
            .fire-icon {
                font-size: 1.5rem;
            }
            
            .student-name {
                font-size: 0.8rem;
            }
            
            .congrats-dialog h2 {
                font-size: 2.5rem;
            }
            
            .congrats-dialog p {
                font-size: 1.2rem;
            }
        }
    </style>
</head>
<body>
    <!-- 音效元素 -->
    <audio id="studentCompleteSound" preload="auto">
        <source src="https://assets.mixkit.co/active_storage/sfx/3060/3060.wav" type="audio/wav">
    </audio>
    <audio id="groupCompleteSound" preload="auto">
        <source src="https://assets.mixkit.co/active_storage/sfx/519/519.wav" type="audio/wav">
    </audio>
    <audio id="classCompleteSound" preload="auto">
        <source src="https://assets.mixkit.co/active_storage/sfx/476/476.wav" type="audio/wav">
    </audio>
    <audio id="resetSound" preload="auto">
        <source src="https://assets.mixkit.co/active_storage/sfx/1334/1334.wav" type="audio/wav">
    </audio>
    
    <div class="container">
        <header>
            <h1>交作业我灭火！</h1>
            <div class="date-bar">
                <div class="import-export-buttons">
                    <button id="importBtn">
                        <i class="fas fa-file-import"></i> 导入名单
                    </button>
                    <button id="exportTemplateBtn">
                        <i class="fas fa-file-export"></i> 导出模板
                    </button>
                </div>
                <span id="currentDate"></span>
                <div class="button-group">
                    <button id="resetBtn">
                        <i class="fas fa-undo"></i> 重置全班
                    </button>
                    <button id="saveBtn">
                        <i class="fas fa-save"></i> 保存进度
                    </button>
                </div>
            </div>
        </header>
        
        <!-- 教室布局 -->
        <div class="classroom">
            <div class="teacher-area">
                <div class="front-left group-1" id="frontLeftStudents"></div>
                <div class="teacher-desk">讲台</div>
                <div class="front-right group-4" id="frontRightStudents"></div>
            </div>
            
            <div class="groups-container">
                <div class="student-group group-1">
                    <div class="group-title" data-group="1">第一组</div>
                    <div class="group-students" id="group1"></div>
                </div>
                <div class="student-group group-2">
                    <div class="group-title" data-group="2">第二组</div>
                    <div class="group-students" id="group2"></div>
                </div>
                <div class="student-group group-3">
                    <div class="group-title" data-group="3">第三组</div>
                    <div class="group-students" id="group3"></div>
                </div>
                <div class="student-group group-4">
                    <div class="group-title" data-group="4">第四组</div>
                    <div class="group-students" id="group4"></div>
                </div>
            </div>
        </div>
    </div>
    
    <div class="instructions">
        <h3>使用说明</h3>
        <ul>
            <li><strong>学生分布</strong>：系统包含最多56名学生，每组各14人，讲台左侧2名属于第一组，讲台右侧2名属于第四组</li>
            <li><strong>导入名单</strong>：点击"导入名单"按钮，可导入Excel格式(.xls或.xlsx)的学生名单</li>
            <li><strong>导出模板</strong>：点击"导出模板"按钮，获取标准格式的Excel模板</li>
            <li><strong>标记/取消标记</strong>：单击学生火苗图标可切换完成状态，并播放相应音效</li>
            <li><strong>组操作</strong>：点击组名可以一键切换全组学生的完成状态</li>
            <li><strong>保存进度</strong>：点击"保存进度"按钮会保存当前状态，下次打开自动加载</li>
            <li><strong>重置全班</strong>：点击"重置全班"按钮会将所有学生状态重置为未完成</li>
        </ul>
    </div>
    
    <!-- 对话框 -->
    <div class="dialog-overlay" id="classDialogOverlay">
        <div class="congrats-dialog">
            <h2>5班最棒！</h2>
            <p>所有作业已完成收集！</p>
            <button class="close-dialog">继续</button>
        </div>
    </div>
    
    <div class="dialog-overlay" id="groupDialogOverlay">
        <div class="congrats-dialog group-congrats-dialog">
            <h2>太棒了！</h2>
            <p id="groupDialogMessage">第一组全部完成！</p>
            <button class="close-dialog">继续</button>
        </div>
    </div>
    
    <div class="dialog-overlay" id="resetConfirmDialog">
        <div class="congrats-dialog group-congrats-dialog">
            <h2>确认重置？</h2>
            <p>是否将所有学生状态重置为未完成？</p>
            <div style="display: flex; gap: 15px; justify-content: center;">
                <button id="confirmResetBtn" class="close-dialog">确认</button>
                <button id="cancelResetBtn" class="close-dialog">取消</button>
            </div>
        </div>
    </div>
    
    <div class="dialog-overlay" id="importInfoDialog">
        <div class="congrats-dialog info-dialog">
            <h2>导入成功</h2>
            <p id="importInfoMessage">已成功导入56名学生</p>
            <button class="close-dialog">确定</button>
        </div>
    </div>
    
    <div class="dialog-overlay" id="importErrorDialog">
        <div class="congrats-dialog info-dialog">
            <h2>导入失败</h2>
            <p id="importErrorMessage">文件格式不正确，请使用Excel文件</p>
            <div class="import-guide">
                <h4>正确格式要求：</h4>
                <ul>
                    <li>文件必须是.xls或.xlsx格式</li>
                    <li>第一行应为标题行：序号、姓名</li>
                    <li>包含56行学生数据（序号1-56）</li>
                    <li>请先导出模板并按模板填写</li>
                </ul>
            </div>
            <button class="close-dialog">确定</button>
        </div>
    </div>
    
    <div class="sync-indicator" id="syncIndicator">
        <i class="fas fa-sync-alt fa-spin"></i>
        <span>状态已同步</span>
    </div>
    
    <input type="file" id="fileInput" accept=".xls,.xlsx" style="display: none;">
    
    <script>
        // 确保DOM完全加载后再执行代码
        document.addEventListener('DOMContentLoaded', function() {
            try {
                // 全局变量声明
                let students = [];
                let currentDate, importBtn, exportTemplateBtn, saveBtn, resetBtn;
                let fileInput, classDialogOverlay, groupDialogOverlay, resetConfirmDialog;
                let importInfoDialog, importErrorDialog, importInfoMessage, importErrorMessage;
                let confirmResetBtn, cancelResetBtn, groupDialogMessage, syncIndicator;
                let closeDialogButtons;
                let studentCompleteSound, groupCompleteSound, classCompleteSound;
                let resetSound;
                let frontLeftContainer, frontRightContainer, group1Container, group2Container;
                let group3Container, group4Container;
                
                // 座位分配：每组14人，共56人
                const seatDistribution = {
                    frontLeft: 2,    // 讲台左侧 2名 - 属于第一组
                    frontRight: 2,   // 讲台右侧 2名 - 属于第四组
                    group1: 12,      // 第一组额外12名 + 讲台左侧2名 = 14人
                    group2: 14,      // 第二组 14名
                    group3: 14,      // 第三组 14名
                    group4: 12       // 第四组额外12名 + 讲台右侧2名 = 14人
                };
                
                // 初始化DOM元素引用
                function initDOMReferences() {
                    currentDate = document.getElementById('currentDate');
                    importBtn = document.getElementById('importBtn');
                    exportTemplateBtn = document.getElementById('exportTemplateBtn');
                    saveBtn = document.getElementById('saveBtn');
                    resetBtn = document.getElementById('resetBtn');
                    fileInput = document.getElementById('fileInput');
                    classDialogOverlay = document.getElementById('classDialogOverlay');
                    groupDialogOverlay = document.getElementById('groupDialogOverlay');
                    resetConfirmDialog = document.getElementById('resetConfirmDialog');
                    importInfoDialog = document.getElementById('importInfoDialog');
                    importErrorDialog = document.getElementById('importErrorDialog');
                    importInfoMessage = document.getElementById('importInfoMessage');
                    importErrorMessage = document.getElementById('importErrorMessage');
                    confirmResetBtn = document.getElementById('confirmResetBtn');
                    cancelResetBtn = document.getElementById('cancelResetBtn');
                    groupDialogMessage = document.getElementById('groupDialogMessage');
                    syncIndicator = document.getElementById('syncIndicator');
                    closeDialogButtons = document.querySelectorAll('.close-dialog');
                    
                    // 音效元素
                    studentCompleteSound = document.getElementById('studentCompleteSound');
                    groupCompleteSound = document.getElementById('groupCompleteSound');
                    classCompleteSound = document.getElementById('classCompleteSound');
                    resetSound = document.getElementById('resetSound');
                    
                    // 座位容器
                    frontLeftContainer = document.getElementById('frontLeftStudents');
                    frontRightContainer = document.getElementById('frontRightStudents');
                    group1Container = document.getElementById('group1');
                    group2Container = document.getElementById('group2');
                    group3Container = document.getElementById('group3');
                    group4Container = document.getElementById('group4');
                }
                
                function startApplication() {
                    // 设置当前日期
                    setCurrentDate();
                    
                    // 注册事件监听器
                    registerEventListeners();
                    
                    // 初始化教室布局
                    initializeClassroom();
                    
                    // 显示同步提示
                    showSyncIndicator();
                }
                
                // 注册所有事件监听器
                function registerEventListeners() {
                    if (importBtn) {
                        importBtn.addEventListener('click', () => {
                            if (fileInput) fileInput.click();
                        });
                    }
                    
                    if (exportTemplateBtn) {
                        exportTemplateBtn.addEventListener('click', exportTemplate);
                    }
                    
                    if (fileInput) {
                        fileInput.addEventListener('change', (e) => {
                            if (e.target.files.length > 0) {
                                importStudentList(e.target.files[0]);
                                fileInput.value = '';
                            }
                        });
                    }
                    
                    if (saveBtn) {
                        saveBtn.addEventListener('click', () => {
                            saveToLocalStorage();
                            if (syncIndicator) {
                                syncIndicator.querySelector('span').textContent = '状态已保存';
                                showSyncIndicator();
                            }
                        });
                    }
                    
                    // 重置按钮事件
                    if (resetBtn) {
                        resetBtn.addEventListener('click', () => {
                            if (resetConfirmDialog) resetConfirmDialog.classList.add('active');
                        });
                    }
                    
                    // 确认重置
                    if (confirmResetBtn) {
                        confirmResetBtn.addEventListener('click', () => {
                            resetAllCompletion();
                            if (resetConfirmDialog) resetConfirmDialog.classList.remove('active');
                        });
                    }
                    
                    // 取消重置
                    if (cancelResetBtn) {
                        cancelResetBtn.addEventListener('click', () => {
                            if (resetConfirmDialog) resetConfirmDialog.classList.remove('active');
                        });
                    }
                    
                    // 关闭对话框按钮事件
                    closeDialogButtons.forEach(button => {
                        button.addEventListener('click', () => {
                            if (classDialogOverlay) classDialogOverlay.classList.remove('active');
                            if (groupDialogOverlay) groupDialogOverlay.classList.remove('active');
                            if (resetConfirmDialog) resetConfirmDialog.classList.remove('active');
                            if (importInfoDialog) importInfoDialog.classList.remove('active');
                            if (importErrorDialog) importErrorDialog.classList.remove('active');
                            if (classCompleteSound) classCompleteSound.pause();
                            if (groupCompleteSound) groupCompleteSound.pause();
                        });
                    });
                    
                    // 点击对话框背景关闭
                    const dialogs = [classDialogOverlay, groupDialogOverlay, resetConfirmDialog, importInfoDialog, importErrorDialog];
                    dialogs.forEach(dialog => {
                        if (dialog) {
                            dialog.addEventListener('click', (e) => {
                                if (e.target === dialog) {
                                    dialog.classList.remove('active');
                                    if (dialog === classDialogOverlay && classCompleteSound) classCompleteSound.pause();
                                    if (dialog === groupDialogOverlay && groupCompleteSound) groupCompleteSound.pause();
                                }
                            });
                        }
                    });
                }
                
                // 设置当前日期
                function setCurrentDate() {
                    const now = new Date();
                    const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
                    currentDate.textContent = now.toLocaleDateString('zh-CN', options);
                }
                
                // 获取容器所属的组ID
                function getContainerGroupId(container) {
                    // 检查是否是讲台左右的学生
                    if (container.id === 'frontLeftStudents') return '1';
                    if (container.id === 'frontRightStudents') return '4';
                    
                    // 检查是哪个组的容器
                    if (container.closest('.student-group.group-1')) return '1';
                    if (container.closest('.student-group.group-2')) return '2';
                    if (container.closest('.student-group.group-3')) return '3';
                    if (container.closest('.student-group.group-4')) return '4';
                    
                    return '1'; // 默认第一组
                }
                
                // 创建学生元素
                function createStudentElement(student) {
                    // 如果姓名为空，不创建卡片
                    if (!student.name || student.name.trim() === '') {
                        return null;
                    }
                    
                    const fireItem = document.createElement('div');
                    fireItem.className = `fire-item group-${student.group}`;
                    fireItem.dataset.id = student.id;
                    fireItem.dataset.group = student.group;
                    
                    // 学生编号显示
                    const studentId = document.createElement('div');
                    studentId.className = 'student-id';
                    studentId.textContent = student.id;
                    
                    const fireIcon = document.createElement('div');
                    fireIcon.className = 'fire-icon';
                    fireIcon.innerHTML = '<i class="fas fa-fire"></i>';
                    
                    const studentName = document.createElement('div');
                    studentName.className = 'student-name';
                    studentName.textContent = student.name;
                    
                    if (student.completed) {
                        fireItem.classList.add('completed');
                    }
                    
                    fireItem.appendChild(studentId);
                    fireItem.appendChild(fireIcon);
                    fireItem.appendChild(studentName);
                    
                    // 添加点击事件 - 单击切换状态
                    fireItem.addEventListener('click', () => {
                        toggleCompletion(student.id);
                    });
                    
                    return fireItem;
                }
                
                // 初始化教室布局
                function initializeClassroom() {
                    console.log("初始化教室布局，显示学生卡片");
                    
                    // 清空所有容器
                    frontLeftContainer.innerHTML = '';
                    frontRightContainer.innerHTML = '';
                    group1Container.innerHTML = '';
                    group2Container.innerHTML = '';
                    group3Container.innerHTML = '';
                    group4Container.innerHTML = '';
                    
                    // 添加讲台左侧学生 (属于第一组)
                    const frontLeftStudents = students.filter(s => s.position === 'frontLeft' && s.name && s.name.trim() !== '');
                    console.log(`讲台左侧学生数: ${frontLeftStudents.length}`);
                    frontLeftStudents.forEach(student => {
                        const element = createStudentElement(student);
                        if (element) frontLeftContainer.appendChild(element);
                    });
                    
                    // 添加讲台右侧学生 (属于第四组)
                    const frontRightStudents = students.filter(s => s.position === 'frontRight' && s.name && s.name.trim() !== '');
                    console.log(`讲台右侧学生数: ${frontRightStudents.length}`);
                    frontRightStudents.forEach(student => {
                        const element = createStudentElement(student);
                        if (element) frontRightContainer.appendChild(element);
                    });
                    
                    // 添加第一组学生
                    const group1Students = students.filter(s => s.position === 'group1' && s.name && s.name.trim() !== '');
                    console.log(`第一组学生数: ${group1Students.length}`);
                    addStudentsInRows(group1Container, group1Students);
                    
                    // 添加第二组学生
                    const group2Students = students.filter(s => s.position === 'group2' && s.name && s.name.trim() !== '');
                    console.log(`第二组学生数: ${group2Students.length}`);
                    addStudentsInRows(group2Container, group2Students);
                    
                    // 添加第三组学生
                    const group3Students = students.filter(s => s.position === 'group3' && s.name && s.name.trim() !== '');
                    console.log(`第三组学生数: ${group3Students.length}`);
                    addStudentsInRows(group3Container, group3Students);
                    
                    // 添加第四组学生
                    const group4Students = students.filter(s => s.position === 'group4' && s.name && s.name.trim() !== '');
                    console.log(`第四组学生数: ${group4Students.length}`);
                    addStudentsInRows(group4Container, group4Students);
                    
                    // 添加组名点击事件
                    document.querySelectorAll('.group-title').forEach(title => {
                        title.addEventListener('click', () => {
                            toggleGroupCompletion(parseInt(title.dataset.group));
                        });
                    });
                    
                    // 初始化组完成状态标记
                    document.querySelectorAll('.group-title').forEach(title => {
                        title.dataset.completed = "false";
                    });
                    
                    // 检查各组完成状态
                    checkGroupCompletion();
                }
                
                // 辅助函数：将学生按行添加（每行2名同桌）
                function addStudentsInRows(container, studentsList) {
                    let currentRow;
                    
                    studentsList.forEach((student, index) => {
                        // 每2名学生创建一个新行
                        if (index % 2 === 0) {
                            currentRow = document.createElement('div');
                            currentRow.className = 'student-row';
                            container.appendChild(currentRow);
                        }
                        
                        const element = createStudentElement(student);
                        if (element) currentRow.appendChild(element);
                    });
                    
                    // 如果最后一行只有一个学生，添加一个占位符
                    if (studentsList.length % 2 !== 0) {
                        const placeholder = document.createElement('div');
                        placeholder.className = 'fire-item drop-zone';
                        placeholder.style.visibility = 'hidden'; // 隐藏占位符
                        currentRow.appendChild(placeholder);
                    }
                }
                
                // 切换单个学生完成状态（单击即可标记或取消标记）
                function toggleCompletion(id) {
                    const student = students.find(s => s.id === id);
                    if (!student) return;
                    
                    const wasCompleted = student.completed;
                    student.completed = !wasCompleted;
                    
                    document.querySelectorAll(`.fire-item[data-id="${id}"]`).forEach(item => {
                        if (student.completed) {
                            item.classList.add('completed');
                            createFireAnimation(item);
                            // 播放完成音效
                            playStudentCompleteSound();
                        } else {
                            item.classList.remove('completed');
                            // 播放取消标记音效（使用重置音效）
                            playResetSound();
                        }
                    });
                    
                    checkGroupCompletion();
                    saveToLocalStorage();
                    checkAllCompleted();
                }
                
                // 切换整个组的完成状态
                function toggleGroupCompletion(groupId) {
                    const groupStudents = students.filter(s => s.group === groupId.toString() && s.name && s.name.trim() !== '');
                    
                    if (groupStudents.length === 0) return;
                    
                    const allCompleted = groupStudents.every(s => s.completed);
                    const newState = !allCompleted;
                    
                    groupStudents.forEach(student => {
                        student.completed = newState;
                        
                        document.querySelectorAll(`.fire-item[data-id="${student.id}"]`).forEach(item => {
                            if (newState) {
                                item.classList.add('completed');
                                if (!allCompleted) {
                                    createFireAnimation(item);
                                }
                            } else {
                                item.classList.remove('completed');
                            }
                        });
                    });
                    
                    if (newState) {
                        playStudentCompleteSound();
                    } else {
                        playResetSound();
                    }
                    
                    checkGroupCompletion();
                    saveToLocalStorage();
                    checkAllCompleted();
                }
                
                // 播放音效函数
                function playStudentCompleteSound() {
                    if (studentCompleteSound) {
                        studentCompleteSound.currentTime = 0;
                        studentCompleteSound.play().catch(e => {
                            console.log("无法播放学生完成音效:", e);
                        });
                    }
                }
                
                function playGroupCompleteSound() {
                    if (groupCompleteSound) {
                        groupCompleteSound.currentTime = 0;
                        groupCompleteSound.play().catch(e => {
                            console.log("无法播放小组完成音效:", e);
                        });
                    }
                }
                
                function playClassCompleteSound() {
                    if (classCompleteSound) {
                        classCompleteSound.currentTime = 0;
                        classCompleteSound.play().catch(e => {
                            console.log("无法播放全班完成音效:", e);
                        });
                    }
                }
                
                function playResetSound() {
                    if (resetSound) {
                        resetSound.currentTime = 0;
                        resetSound.play().catch(e => {
                            console.log("无法播放重置音效:", e);
                        });
                    }
                }
                
                // 重置全班学生完成状态
                function resetAllCompletion() {
                    students.forEach(student => {
                        student.completed = false;
                    });
                    
                    document.querySelectorAll('.fire-item').forEach(item => {
                        item.classList.remove('completed');
                    });
                    
                    checkGroupCompletion();
                    saveToLocalStorage();
                    showSyncIndicator();
                    
                    // 播放重置音效
                    playResetSound();
                }
                
                // 检查组完成情况
                function checkGroupCompletion() {
                    for (let groupId = 1; groupId <= 4; groupId++) {
                        const groupStudents = students.filter(s => 
                            s.group === groupId.toString() && s.name && s.name.trim() !== ''
                        );
                        
                        if (groupStudents.length === 0) continue;
                        
                        const allCompleted = groupStudents.every(s => s.completed);
                        const groupTitle = document.querySelector(`.group-title[data-group="${groupId}"]`);
                        
                        if (allCompleted) {
                            groupTitle.classList.add('completed');
                            if (groupTitle.dataset.completed !== "true") {
                                groupTitle.dataset.completed = "true";
                                playGroupCompleteSound();
                                showGroupCompletionDialog(groupId);
                            }
                        } else {
                            groupTitle.classList.remove('completed');
                            groupTitle.dataset.completed = "false";
                        }
                    }
                }
                
                // 显示组完成庆祝对话框
                function showGroupCompletionDialog(groupId) {
                    const groupNames = ["", "第一组", "第二组", "第三组", "第四组"];
                    groupDialogMessage.textContent = `${groupNames[groupId]}全部完成！`;
                    groupDialogOverlay.classList.add('active');
                    setTimeout(() => {
                        groupDialogOverlay.classList.remove('active');
                    }, 5000);
                }
                
                // 创建火苗动画
                function createFireAnimation(element) {
                    const rect = element.getBoundingClientRect();
                    const centerX = rect.left + rect.width / 2;
                    const centerY = rect.top + rect.height / 2;
                    
                    for (let i = 0; i < 15; i++) {
                        setTimeout(() => {
                            const particle = document.createElement('div');
                            particle.className = 'fire-particle';
                            
                            // 随机位置
                            const angle = Math.random() * Math.PI * 2;
                            const distance = Math.random() * 50 + 20;
                            const x = centerX + Math.cos(angle) * distance;
                            const y = centerY + Math.sin(angle) * distance;
                            
                            particle.style.left = `${x}px`;
                            particle.style.top = `${y}px`;
                            
                            // 随机大小
                            const size = Math.random() * 6 + 2;
                            particle.style.width = `${size}px`;
                            particle.style.height = `${size}px`;
                            
                            document.body.appendChild(particle);
                            
                            // 动画
                            const duration = Math.random() * 1000 + 500;
                            particle.animate([
                                { opacity: 1, transform: 'scale(1)' },
                                { opacity: 0, transform: 'scale(0.2)' }
                            ], {
                                duration: duration,
                                easing: 'ease-out'
                            });
                            
                            // 移除元素
                            setTimeout(() => {
                                particle.remove();
                            }, duration);
                        }, i * 50);
                    }
                }
                
                // 检查是否全部完成
                function checkAllCompleted() {
                    const activeStudents = students.filter(s => s.name && s.name.trim() !== '');
                    const allCompleted = activeStudents.every(student => student.completed);
                    
                    if (allCompleted && activeStudents.length > 0) {
                        setTimeout(() => {
                            classDialogOverlay.classList.add('active');
                            playClassCompleteSound();
                        }, 500);
                    }
                }
                
                // 导入Excel学生名单
                function importStudentList(file) {
                    // 检查XLSX是否可用
                    if (typeof XLSX === 'undefined') {
                        showImportError("Excel处理库未加载，请刷新页面重试");
                        return;
                    }
                    
                    const reader = new FileReader();
                    
                    reader.onload = function(e) {
                        try {
                            const data = new Uint8Array(e.target.result);
                            const workbook = XLSX.read(data, { type: 'array' });
                            
                            const firstSheetName = workbook.SheetNames[0];
                            const worksheet = workbook.Sheets[firstSheetName];
                            
                            const jsonData = XLSX.utils.sheet_to_json(worksheet);
                            
                            if (!validateStudentData(jsonData)) {
                                showImportError("数据格式不正确，请检查是否符合模板要求");
                                return;
                            }
                            
                            let importedCount = 0;
                            jsonData.forEach(item => {
                                const id = parseInt(item.序号 || item['序号']);
                                if (id && id >= 1 && id <= 56) {
                                    const student = students.find(s => s.id === id);
                                    if (student) {
                                        // 保存学生的完成状态和位置信息
                                        const completedState = student.completed;
                                        const position = student.position;
                                        const group = student.group;
                                        
                                        // 更新学生姓名
                                        student.name = item.姓名 || item['姓名'] || '';
                                        
                                        // 恢复完成状态和位置信息
                                        student.completed = completedState;
                                        student.position = position;
                                        student.group = group;
                                        
                                        importedCount++;
                                    }
                                }
                            });
                            
                            initializeClassroom();
                            saveToLocalStorage();
                            showSyncIndicator();
                            
                            importInfoMessage.textContent = `已成功导入 ${importedCount} 名学生`;
                            importInfoDialog.classList.add('active');
                            
                        } catch (error) {
                            console.error("导入失败:", error);
                            showImportError("导入失败: " + error.message);
                        }
                    };
                    
                    reader.onerror = function() {
                        showImportError("无法读取文件，请尝试其他文件");
                    };
                    
                    reader.readAsArrayBuffer(file);
                }
                
                // 验证学生数据格式
                function validateStudentData(data) {
                    if (data.length < 56) return false;
                    
                    const firstItem = data[0];
                    if (!firstItem.hasOwnProperty('序号') && !firstItem.hasOwnProperty('序号')) return false;
                    if (!firstItem.hasOwnProperty('姓名') && !firstItem.hasOwnProperty('姓名')) return false;
                    
                    const ids = new Set();
                    data.forEach(item => {
                        const id = parseInt(item.序号 || item['序号']);
                        if (!isNaN(id)) ids.add(id);
                    });
                    
                    for (let i = 1; i <= 56; i++) {
                        if (!ids.has(i)) return false;
                    }
                    
                    return true;
                }
                
                // 显示导入错误
                function showImportError(message) {
                    importErrorMessage.textContent = message;
                    importErrorDialog.classList.add('active');
                }
                
                // 导出Excel模板
                function exportTemplate() {
                    // 检查XLSX是否可用
                    if (typeof XLSX === 'undefined') {
                        showImportError("Excel处理库未加载，请刷新页面重试");
                        return;
                    }
                    
                    try {                    
                        const templateData = [];
                        
                        // 仅添加一行表头
                        templateData.push({
                            '序号': '序号',
                            '姓名': '姓名'
                        });
                        
                        // 从1到56添加序号
                        for (let i = 1; i <= 56; i++) {
                            // 查找当前学生姓名
                            const student = students.find(s => s.id === i);
                            const studentName = student ? student.name : '';
                            
                            templateData.push({
                                '序号': i,
                                '姓名': studentName
                            });
                        }
                        
                        const worksheet = XLSX.utils.json_to_sheet(templateData);
                        
                        // 设置列宽
                        const wscols = [
                            {wch: 6},  // 序号列宽度
                            {wch: 15}  // 姓名列宽度
                        ];
                        worksheet['!cols'] = wscols;
                        
                        const workbook = XLSX.utils.book_new();
                        XLSX.utils.book_append_sheet(workbook, worksheet, '学生名单');
                        
                        XLSX.writeFile(workbook, '学生名单模板.xlsx');
                        
                        syncIndicator.querySelector('span').textContent = '模板已导出';
                        showSyncIndicator();
                    } catch (error) {
                        console.error("导出模板失败:", error);
                        showImportError("导出模板失败: " + error.message);
                    }
                }
                
                // 保存到本地存储
                function saveToLocalStorage() {
                    try {
                        localStorage.setItem('fireHomeworkTracker', JSON.stringify({
                            students: students,
                            lastUpdated: new Date().toISOString()
                        }));
                    } catch (error) {
                        console.error("保存数据失败:", error);
                    }
                }
                
                // 显示同步指示器
                function showSyncIndicator() {
                    syncIndicator.classList.add('active');
                    setTimeout(() => {
                        syncIndicator.classList.remove('active');
                    }, 3000);
                }
                
                // 初始化56名学生，分配到各个位置
                function initializeDefaultStudents() {
                    students = [];
                    let id = 1;
                    
                    // 讲台左侧 (2名) - 第一组
                    for (let i = 0; i < 2; i++) {
                        students.push({
                            id: id++,
                            name: `学生${id-1}`,
                            completed: false,
                            position: 'frontLeft',
                            group: '1'
                        });
                    }
                    
                    // 第一组 (12名)
                    for (let i = 0; i < 12; i++) {
                        students.push({
                            id: id++,
                            name: `学生${id-1}`,
                            completed: false,
                            position: 'group1',
                            group: '1'
                        });
                    }
                    
                    // 第二组 (14名)
                    for (let i = 0; i < 14; i++) {
                        students.push({
                            id: id++,
                            name: `学生${id-1}`,
                            completed: false,
                            position: 'group2',
                            group: '2'
                        });
                    }
                    
                    // 第三组 (14名)
                    for (let i = 0; i < 14; i++) {
                        students.push({
                            id: id++,
                            name: `学生${id-1}`,
                            completed: false,
                            position: 'group3',
                            group: '3'
                        });
                    }
                    
                    // 第四组 (12名)
                    for (let i = 0; i < 12; i++) {
                        students.push({
                            id: id++,
                            name: `学生${id-1}`,
                            completed: false,
                            position: 'group4',
                            group: '4'
                        });
                    }
                    
                    // 讲台右侧 (2名) - 第四组
                    for (let i = 0; i < 2; i++) {
                        students.push({
                            id: id++,
                            name: `学生${id-1}`,
                            completed: false,
                            position: 'frontRight',
                            group: '4'
                        });
                    }
                    
                    // 确保正好56名学生
                    console.log(`已初始化 ${students.length} 名学生`);
                }
                
                // 初始化应用程序
                function initApp() {
                    // 初始化DOM引用
                    initDOMReferences();
                    
                    // 尝试从本地存储加载数据，如果没有则初始化56名学生
                    const savedData = localStorage.getItem('fireHomeworkTracker');
                    if (savedData) {
                        try {
                            const parsedData = JSON.parse(savedData);
                            students = parsedData.students || [];
                            console.log(`从本地存储加载了 ${students.length} 名学生`);
                        } catch (e) {
                            console.error('加载本地存储数据失败:', e);
                            initializeDefaultStudents();
                        }
                    } else {
                        initializeDefaultStudents();
                    }
                    
                    // 检查XLSX库是否加载成功
                    if (typeof XLSX === 'undefined') {
                        console.error('XLSX库未加载成功，尝试重新加载...');
                        
                        // 动态创建并加载XLSX库
                        const script = document.createElement('script');
                        script.src = 'https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js';
                        script.onload = function() {
                            console.log('XLSX库重新加载成功');
                            startApplication();
                        };
                        script.onerror = function() {
                            console.error('XLSX库加载失败，请检查网络连接');
                            alert('导出功能依赖的库加载失败，请刷新页面重试');
                            startApplication(); // 即使XLSX加载失败，也初始化其他功能
                        };
                        document.head.appendChild(script);
                    } else {
                        startApplication();
                    }
                }
                
                // 启动应用程序
                initApp();
            } catch (error) {
                console.error("应用程序初始化失败:", error);
                // 显示友好的错误消息给用户
                alert("页面加载时出现错误: " + error.message + "\n请尝试刷新页面");
                
                // 创建一个简单的备用界面
                document.body.innerHTML = `
                    <div style="text-align: center; padding: 20px;">
                        <h1>加载失败</h1>
                        <p>页面加载时出现错误，请尝试刷新页面</p>
                        <button onclick="window.location.reload()" style="padding: 10px 20px; font-size: 16px;">
                            刷新页面
                        </button>
                    </div>
                `;
            }
        });
    </script>
</body>
</html>
    